package com.onenine.app.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.sdk.android.manager.OssManager;
import com.onenine.app.R;
import com.onenine.app.activity.LoginActivity;
import com.onenine.app.activity.MainActivity;
import com.onenine.app.event.FinishEvent;
import com.onenine.app.event.PermissionsEvent;
import com.onenine.app.listener.OnLoginListener;
import com.onenine.app.model.ThirdPlatform;
import com.onenine.app.request.InfoSubmitRequest;
import com.onenine.app.request.QQLoginRequest;
import com.onenine.app.request.WeiXinRequest;
import com.onenine.app.response.LoginResponse;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.LoadingButton;
import com.onenine.app.view.date.DatePickerPopWin;
import com.onenine.app.view.uppanel.SlidingUpPanelLayout;
import com.onenine.base.okhttp.BaseRequest;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.FragmentUtils;
import com.onenine.common.util.KeyboardUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.ScreenUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 录入资料
 */
public class LoginInputInfoFragment extends Fragment implements View.OnClickListener
        , EasyPermissions.PermissionCallbacks, RadioGroup.OnCheckedChangeListener {

    private final String[] mPermissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static final int RC_AVATAR = 0x0001;
    private TextView mTvBirthday;
    private EditText mEdtNick;
    private LoadingButton mBtnLoading;
    private ImageView mIvHeadPic;
    private RadioGroup mRgSex;
    private int mCheckedSex;
    private OnLoginListener mOnLoginListener;
    private String mUserId;
    private ThirdPlatform mThirdPlatform;
    private LoginResponse mLoginResponse;
    private SlidingUpPanelLayout mUpPanelLayout;

    /**
     * 手机号登录填写资料
     *
     * @param userId
     * @return
     */
    public static Fragment newInstance(String userId) {
        Fragment fragment = new LoginInputInfoFragment();
        Bundle args = new Bundle();
        args.putString("userId", userId);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 微信QQ第三方登录
     *
     * @param thirdMap
     * @return
     */
    public static Fragment newInstance(Map<String, String> thirdMap) {
        Fragment fragment = new LoginInputInfoFragment();
        Bundle args = new Bundle();
        args.putSerializable("data", (Serializable) thirdMap);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mUpPanelLayout.setTouchEnabled(false);
        if (mCheckedSex > 0) {
            mOnLoginListener.updateBackground(mCheckedSex);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mUpPanelLayout.setTouchEnabled(true);
        if (mCheckedSex > 0) {
            mOnLoginListener.updateBackground(0);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mOnLoginListener = (OnLoginListener) getActivity();
        Bundle args = getArguments();
        if (args.containsKey("data")) {
            mThirdPlatform = new ThirdPlatform((Map<String, String>) args
                    .getSerializable("data"));
            mEdtNick.setText(mThirdPlatform.getName());
            GlideUtils.loadCircleAvatar(this, mIvHeadPic, mThirdPlatform.getIconurl());
            if (CHelper.isMaleStr(mThirdPlatform.getGender())) {
                mRgSex.check(R.id.rb_male);
                mThirdPlatform.setGender(DataType.SEX_MALE + "");
            } else if (CHelper.isFemaleStr(mThirdPlatform.getGender())) {
                mRgSex.check(R.id.rb_female);
                mThirdPlatform.setGender(DataType.SEX_FEMALE + "");
            }
        } else if (args.containsKey("userId")) {
            mUserId = args.getString("userId");
        }
        mRgSex.check(R.id.rb_female);
        mUpPanelLayout = mOnLoginListener.getUpPanelLayout();
        mUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
        KeyboardUtils.hideSoftInput(mEdtNick);
        mEdtNick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login_input_info, container, false);
        mIvHeadPic = view.findViewById(R.id.iv_headpic);
        mTvBirthday = view.findViewById(R.id.tv_birthday);
        mEdtNick = view.findViewById(R.id.edt_name);
        mBtnLoading = view.findViewById(R.id.btn_loading);
        mBtnLoading.setButtonEnable(false);
        mBtnLoading.setButtonText(R.string.next_step);
        mRgSex = view.findViewById(R.id.rg_sex);
        mIvHeadPic.setOnClickListener(this);
        mTvBirthday.setOnClickListener(this);
        mBtnLoading.setButtonOnClickListener(this);
        mRgSex.setOnCheckedChangeListener(this);
        return view;
    }

    /**
     * 加载权限相册
     */
    protected void launchPermissionAlbum() {
        if (EasyPermissions.hasPermissions(getActivity(), mPermissions)) {
            launchMatisseAlbum();
        } else {
            EasyPermissions.requestPermissions(getActivity(), getString(R.string.permission_camera_hint)
                    , RC_AVATAR, mPermissions);
        }
    }

    /**
     * 拉起相册
     */
    private void launchMatisseAlbum() {
        Matisse.from(getActivity())
                .choose(MimeType.ofImage())//只显示照片
                .capture(true)
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .captureStrategy(new CaptureStrategy(true, getActivity().getPackageName() + ".fileprovider"))
                .countable(false)//有序选择图片
                .maxSelectable(1)//最大选择数量为9
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(RC_AVATAR);//请求码
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param fileStr
     */
    private void compressImages(final String fileStr) {
        Luban.with(getActivity())
                .load(fileStr).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        showHeadPic(file.getAbsolutePath());
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RC_AVATAR) {
                List<String> pathList = Matisse.obtainPathResult(data);
                if (pathList != null && !pathList.isEmpty()) {
                    compressImages(pathList.get(0));
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PermissionsEvent event) {
        onRequestPermissionsResult(event.requestCode, event.permissions, event.grantResults);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FinishEvent event) {
        if (event.isFinish && mLoginResponse != null) {
            RcUser rcUser = RcUser.getInstance()
                    .setUserId(mLoginResponse.getUserId())
                    .setSex(mLoginResponse.getSex());
            if (mThirdPlatform != null) {
                rcUser.setLoginType(Integer.parseInt(mThirdPlatform.getPlatform()));
            }
            rcUser.applyUser();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == RC_AVATAR && perms.size() == mPermissions.length) {
            launchMatisseAlbum();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(getActivity(), perms)) {
            new AppSettingsDialog.Builder(getActivity()).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == RC_AVATAR) {
            Toasty.showNormal(R.string.permission_camera_hint);
        }
    }

    /**
     * 第三方平台登录
     */
    private void doThirdLogin() {
        String url;
        BaseRequest request;
        if (TextUtils.equals(DataType.QQ_LOGIN + "", mThirdPlatform.getPlatform())) {
            //QQ
            url = UrlConfig.QQ_LOGIN;
            request = new QQLoginRequest(mThirdPlatform);
            ((QQLoginRequest) request).setName(mEdtNick.getText().toString());
        } else {
            //微信
            url = UrlConfig.WEIXIN_LOGIN;
            request = new WeiXinRequest(mThirdPlatform);
            ((WeiXinRequest) request).setNickName(mEdtNick.getText().toString());
        }
        if (url == null) {
            Logger.e("不支持非QQ和微信的其它登录方式");
            return;
        }
        mBtnLoading.setLoading(true);
        OkRequest.getInstance().withUrl(url)
                .withRequest(request).doRequest(LoginActivity.class.getSimpleName(), new OkCallback<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response, String srcData) {
                if (response.isSuccess()) {
                    //去绑定手机
                    mLoginResponse = response;
                    FragmentUtils.replace(getFragmentManager()
                            , LoginMobileFragment.newInstance(response.getUserId()
                                    , mThirdPlatform.getOpenId()), R.id.fl_content, true);
                } else {
                    Toasty.showNormal(response.getMessage());
                }
                mBtnLoading.setLoading(false);
            }
        });
    }

    /**
     * 显示并上传该头像
     *
     * @param filePath
     */
    private void uploadHeadPic(final String filePath) {
        mBtnLoading.setLoading(true);
        OssManager.getInstance(ApUtils.getApp())
                .ossUpload(filePath, new OssManager.Callback() {
                    @Override
                    public void onSuccess(String url) {
                        if (mUserId != null) {
                            submitInfo(url);
                        } else if (mThirdPlatform != null) {
                            mThirdPlatform.setIconurl(url);
                            doThirdLogin();
                        } else {
                            mBtnLoading.setLoading(false);
                        }
                    }

                    @Override
                    public void onProgress(float progress) {

                    }

                    @Override
                    public void onFailure(int errorCode, String errorMsg) {
                        mBtnLoading.setLoading(false);
                    }
                });
    }


    /**
     * 提交个人资料
     */
    private void submitInfo(String imgUrl) {
        if (!mBtnLoading.isLoading()) {
            mBtnLoading.setLoading(true);
        }
        InfoSubmitRequest request = new InfoSubmitRequest();
        request.setUserId(mUserId);
        request.setNickName(mEdtNick.getText().toString());
        request.setBirthday(mTvBirthday.getText().toString());
        request.setSex(mCheckedSex);
        request.setPhoto(imgUrl);
        OkRequest.getInstance().withUrl(UrlConfig.INFO_SUBMIT)
                .withRequest(request).doRequest(getClass().getSimpleName(), new OkCallback<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response, String srcData) {
                if (response.isSuccess()) {
                    RcUser.getInstance().setSex(request.getSex());
                    //完成注册和登录，跳转到主界面，同时关闭前几个页面
                    EventBus.getDefault().post(new FinishEvent(true));
                    ActivityUtils.startActivity(getActivity(), MainActivity.class);
                    mOnLoginListener.finishActivity();
                } else {
                    Toasty.showNormal(response.getMessage());
                }
                mBtnLoading.setLoading(false);
            }
        });
    }


    /**
     * 显示头像
     *
     * @param url
     */
    private void showHeadPic(final String url) {
        mIvHeadPic.setTag(R.id.data_tag, url);
        GlideUtils.loadCircleAvatar(this, mIvHeadPic, url);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mBtnLoading.isLoading()) {
            return;
        }
        if (checkedId == R.id.rb_male) {
            mCheckedSex = DataType.SEX_MALE;
            mOnLoginListener.updateBackground(mCheckedSex);
            mBtnLoading.setButtonEnable(true);
            if (mThirdPlatform != null) {
                mThirdPlatform.setGender(DataType.SEX_MALE + "");
            }
        } else {
            mCheckedSex = DataType.SEX_FEMALE;
            mOnLoginListener.updateBackground(mCheckedSex);
            mBtnLoading.setButtonEnable(true);
            if (mThirdPlatform != null) {
                mThirdPlatform.setGender(DataType.SEX_FEMALE + "");
            }
        }
        mBtnLoading.setButtonStyle(mCheckedSex);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_headpic:
                launchPermissionAlbum();
                break;
            case R.id.tv_birthday:
                KeyboardUtils.hideSoftInput(mEdtNick);
                new DatePickerPopWin.Builder(getActivity(), new DatePickerPopWin.OnDatePickedListener() {
                    @Override
                    public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                        mTvBirthday.setText(dateDesc);
                        if (mThirdPlatform != null) {
                            mThirdPlatform.setBirthday(dateDesc);
                        }
                    }
                }).minYear(1900)
                        .maxYear(2100)
                        .dateChose("1990-1-1")
                        .setWindowWidth(ScreenUtils.getScreenWidth() * 4 / 5)
                        .build(mCheckedSex).showPopWin(getActivity());
                break;
            case R.id.btn_opt:
                if (mUserId != null && mIvHeadPic.getTag(R.id.data_tag) == null) {
                    Toasty.showNormal(R.string.choose_headpic_hint);
                    return;
                }
                if (TextUtils.isEmpty(mEdtNick.getText())) {
                    Toasty.showNormal(R.string.input_nickname_hint);
                    mEdtNick.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(mTvBirthday.getText())) {
                    Toasty.showNormal(R.string.input_birthday_hint);
                    return;
                }
                if (mCheckedSex == 0) {
                    Toasty.showNormal(R.string.select_sex_hint);
                    return;
                }
                if (mUserId != null) {
                    uploadHeadPic(mIvHeadPic.getTag(R.id.data_tag).toString());
                } else if (mThirdPlatform != null) {
                    if (mIvHeadPic.getTag(R.id.data_tag) != null) {
                        uploadHeadPic(mIvHeadPic.getTag(R.id.data_tag).toString());
                    } else if (!TextUtils.isEmpty(mThirdPlatform.getIconurl())) {
                        doThirdLogin();
                    } else {
                        Toasty.showNormal(R.string.choose_headpic_hint);
                    }
                } else {
                    Toasty.showNormal("非法操作");
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
